/**
 * (C) copyright geolabs 2006-2008
 * author: Gérald Fenoy
 */

/**
 * View class
 */
System.require("OctoXml");

View=Controler.extend({ _id: 0 });
View.define({

  tree: {},
  xmlJson: null,
  errorElement: System.document.body,  

  _init: function(){
      //if(arguments.length>0)
      //alert(arguments[0].root);
      this.rootNode=(arguments.length>0&&arguments[0].root)?arguments[0].root:this.errorElement;
      this.id=View._id;
      View._id++;
      this.tree={};
      this.superCall("_init",arguments);
  },

  update: function(xmlJson){
      this.xmlJson=xmlJson;
      this.nbElement=xmlJson.getNbElement();
      
      if(this.debug) 
	this.xmlJson.debug();
     

      this.tree=xmlJson.tree;
      if(this.debug)alert("launch App");
      this.execRequest(""+this.appUrl);
  },

  /**
   * Clean the content of view as xml result if there are more than once
   * element corresponding to the one which is searched.
   *
   */
  clean: function(){
      var curr=this.request.responseXML.getElementsByTagName(arguments[0]);
      for(var j=1;j<curr.length;j++){
	alert("found :"+(j));
	curr[j].parentNode.removeChild(curr[j]);
      }
    },

  setValue: function(tagname,val,el,prefix,index){

      var oldElement=this.request.responseXML.getElementsByTagName(tagname)[0];
      this.clean(tagname);
      
      var currElementIsEmpty=false;
      
      var newElement;
      
      if(oldElement){
	
	newElement=OctoXml.createElement(el[tagname],{ Oclass: tagname, id: tagname+"_"+this.id+"_"+index });

	if(typeof val[tagname] == "object"){
	  
	  var j=0;
	  for(j in val[tagname]){
	    if(val[tagname][j]){
	      
	      try{
		var tmp=eval(prefix+""+val[tagname][j]);
		if(typeof tmp=="object"){
		  try{tmp=tmp["#text"]}catch(e){tmp=tmp["#cdata"]}
		}
		// not safe imho
		if(!tmp){
		  throw("unable to use this attribute"+tmp);
		}
		
		newElement.setAttribute(j,tmp);

		currElementIsEmpty=false;
	      }
	      catch(e){
		currElementIsEmpty=true;

	      }
	      
	    }
	  }

	}
   
	else{
	  var tmp=eval(prefix+val[tagname]);
	  var child=null;
	  if(typeof tmp=="object"){
	    try{
	      tmp=eval(prefix+val[tagname]+'["#cdata"]');
	    }
	    catch(e){
	      try{tmp=eval(prefix+val[tagname]+'["#text"]');}
	      catch(e){/*alert('tmp is null');*/tmp='';}
	    }
	  }
	  if(!tmp)
	    return;
	    //currElementIsEmpty=true;

	  /**
	   * Could contain HTML encoded data ?
	   */
	  var test=1;
	  for(var t=0;t<this.htmlValues.length;t++)
	    if(tagname==this.htmlValues[t]){
	      test=-1;
	      break;
	    }

	  if(test>0){
	    try{
	      newElement.appendChild(OctoXml.getDocument().createTextNode(""+tmp));
	    }
	    catch(e){alert("Unable to appendChild 1 : "+e);}
	  }
	  else{
	    tmp=HTMLEntity.decode(tmp);
	    var tmpswap=tmp;
	    tmp="<div>"+tmp+"</div>";
	
	    var toAdd=null;

	    try{toAdd=OctoXml.parseFromString(tmp);}
	    catch(e){
	      toAdd=OctoXml.getDocument().createTextNode("Printed as html cause not parsable : "+tmpswap);
	    }

	    try{newElement.appendChild(toAdd);}
	    catch(e){
	      try{newElement.appendChild(toAdd.firstChild);}
	      catch(e){alert(e);}
	    }

	  }

	}
	
	if(oldElement.childNodes)
	  for(var t=0;t<oldElement.childNodes.length;t++){
	    try{
	      newElement.appendChild(oldElement.childNodes[t].cloneNode(true));
	    }catch(e){
 	      alert(newElement.xml+" "+oldElement.xml);
	      alert("Unable to appendChild 2 "+e);
	    }
	  }

	var test=oldElement.parentNode.getAttribute("idx");
	if(test){
	  try{ 
	    if(index>=0)
	      oldElement.parentNode.setAttribute("id",test+"_"+this.id+"_"+index);
	    else
	      oldElement.parentNode.setAttribute("id",test+"_"+this.id);
	  }
	  catch(e){ alert("Unable to setAttribute "+e); }
	}
	
	var parent=oldElement.parentNode;

	if(currElementIsEmpty)
	  newElement.setAttribute("style","display:none;");
	
	parent.replaceChild(newElement,oldElement);
	
      }

    },

    newData: function(){

      looproot=this.request.responseXML.getElementsByTagName(this.loop)[0];

      /**
       * ROOT ELEMENTS
       */
      //if(this.debug)alert("Root start");
      var i=0;
      for(i in this.rootValues){
	this.setValue(i,this.rootValues,this.rootElements,"this.tree."+this.root+".",-1);
      }
      //if(this.debug)alert("Root end");

      /**
       * LOOP
       */
      //if(this.debug)alert("Swap start"+looproot); 
      var parent=looproot.parentNode;
      var swap=looproot.childNodes[0].cloneNode(true);
      for(var t=1;t<looproot.childNodes[0].length;t++){
	if(looproot.childNodes[t].nodeName!="#text"){
	  swap=looproot.childNodes[t].cloneNode(true);
	  break;
	}
      }
      //if(this.debug)alert("Swap end"); 

      parent.replaceChild(swap.cloneNode(true),looproot);

      if(this.nbElement>1)
	for(var j=0;j<this.nbElement;j++){
	  var i=0;
	  
	  for(i in this.loopElements){
	    //if(this.debug)
	    //alert("start "+i+" "+"this.tree."+this.root+"."+this.loop+"["+j+"].");
	    this.setValue(i,this.loopValues,this.loopElements,"this.tree."+this.root+"."+this.loop+"["+j+"].",j);
	    //if(this.debug)alert("end "+i);
	  }
	  
	  if(j+1<this.nbElement){
	    parent.appendChild(swap.cloneNode(true));
	  }
	}
      else{

	for(i in this.loopElements){
	  this.setValue(i,this.loopValues,this.loopElements,"this.tree."+this.root+"."+this.loop+".");

	}
      }

      if(!this.replace)
	try{
	  this.rootNode.innerHTML+=OctoXml.serializeToString(this.request.responseXML);
	}
	catch(e){
	  alert("Unable to update "+e);
	}
      else{
	try{
	  this.rootNode.innerHTML=OctoXml.serializeToString(this.request.responseXML);
	}
	catch(e){
	  alert("Unable to update "+e);
	}	
      }
    }
    
    });


OctoView=Class.create({
  existingRun: {},

  runOnceFromElement: function(element,action1,action2){
      if(!existingRun[element.id]){
	var tmp=this.id.split('_');
	existingRun[element.id]={id: tmp[0], containerId: tmp[1], myId: tmp[2], status: false };
      }

      if(!existingRun[element.id].status)
	{eval(action1);existingRun[element.id].status=1;}
      else{eval(action2);existingRun[element.id].status=0;}

    }

  });
